package com.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.media.mapper.TagMapper;
import com.base.model.R;
import com.media.model.Tag;
import com.media.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * @Author: Lenovo
 * @Description: TODO
 * @DateTime: 2023/9/14 15:10
 **/
@Service
public class TagServiceImpl extends ServiceImpl<TagMapper, Tag> implements TagService {

    @Autowired
    private TagMapper tagMapper;

    /**
     * 添加标签
     *
     * @param tag
     * @return
     */
    @Override
    public R<String> saveTag(Tag tag) {
        LambdaQueryWrapper<Tag> qw = new LambdaQueryWrapper<>();
        qw.eq(Tag::getName, tag.getName());
        Tag one = this.getOne(qw);
        if (one != null) {
            return R.error("已存在相同名称的标签");
        }
        boolean save = this.save(tag);
        if (!save) {
            return R.error("标签添加失败");
        }
        return R.success("标签添加成功");
    }

    /**
     * 修改标签名称或描述
     *
     * @param tag
     * @return
     */
    @Override
    public R<String> updateTag(Tag tag) {
        LambdaQueryWrapper<Tag> qw = new LambdaQueryWrapper<>();
        qw.eq(Tag::getName, tag.getName());
        Tag one = this.getOne(qw);
        if (one != null && !Objects.equals(one.getId(), tag.getId())) {
            return R.error("已存在相同名称的标签");
        }
        boolean result = this.updateById(tag);
        if (!result) {
            return R.error("标签修改失败");
        }
        return R.success("标签修改成功");
    }

    /**
     * 删除标签
     *
     * @param Id
     * @return
     */
    @Override
    @Transactional
    public R<String> deleteTag(Integer Id) {
        //1.删除标签表中对应的标签
        boolean result = this.removeById(Id);
        if (!result) {
            return R.error("标签删除失败");
        }
        //2.删除标签视频关联表中的关联信息
        int delete = tagMapper.deleteContactById(Id);
        return R.success("标签修改成功");
    }

    @Override
    public R<List<Tag>> listTag() {
        List<Tag> list = this.list();
        return R.success(list);
    }


}
